var express = require('express');
const UserModel = require('../model/UserModel');
const { route } = require('.');
var router = express.Router();

/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});


// 响应前端的post增加请求
router.post('/user', (req, res) => {
  console.log(req.body);
  /* 
    插入数据库
    1.创建一个模型(user,限制filed类型)，一一对应数据库的集合（user）
    user.create user.find user.delete user.updata 为了提高复用性建议重新创建model文件夹

    2. 引入模块并创建数据
  */
  const { username, address, tel } = req.body
  UserModel.create({
    username, address, tel
  }).then(data => {
    console.log(data);
    res.send({
      ok: 1
    })
  }).catch(err => {
    console.log(err);
  })
})

// 修改
router.put("/user/:id", (req, res) => {
  console.log(req.params.id);
  console.log(req.body);
  const { username, address, tel } = req.body
  UserModel.updateOne({
    _id: req.params.id
  }, { username, address, tel }).then(data => {
    res.send({
      ok: 1
    })
  })
})

router.delete("/user/:id", (req, res) => {
  console.log(req.params.id);
  UserModel.deleteOne({ _id: req.params.id }).then(data => {
    console.log(data);
    res.send({
      ok: 1
    })
  })
})

router.get("/user", (req, res) => {
  console.log(req.query);
  const { page, limit } = req.query
  UserModel.find({}, ["username", "address","tel", "_id"]).sort({ age: 1 }).skip((page - 1) * limit).limit(limit).then(data => {
    res.send(data)
  })
})
module.exports = router;
